package cn.caplike.demo.spring.security.csrf.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Map;

/**
 * 鉴权过滤器: 用于校验请求头中有没有合法的 access-token<br>
 * 除了 /auth/login 之外的所有请求都会经过这个过滤器<br>
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-05-08 09:21
 */
@Slf4j
public class SimpleAuthorizationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        Map<String, String> map = JSON.parseObject(request.getInputStream(), StandardCharsets.UTF_8, Map.class);

        // 认证
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
                MapUtils.getString(map, "username"),
                MapUtils.getString(map, "password"),
                Collections.singletonList((GrantedAuthority) () -> "ADMIN")
        ));

        filterChain.doFilter(request, response);
    }
}
